from cgi import parse_qs
import BaseHTTPServer
import SimpleHTTPServer
import os
import posixpath
import BaseHTTPServer
import urllib
import urlparse
import sys

from browser.utils import get_host

__all__ = ('RCHTTPRequestHandler',)

class RCHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    server_version = 'RCHTTP/1.0'
    current_host = None

    def local_handle(self):
        content_length = int(self.headers.get('Content-Length', 0))
        if not content_length:
            return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        query_string = self.parse_querystring()
        post_data = parse_qs(self.rfile.read(content_length))

        if getattr(self.server, 'last_page', None):
            self.server.finished = True
            self.server.last_page = None

        cmd = self.server.queue.get()

        if len(cmd) > 2 and cmd[-1] == 'finish':
            self.server.last_page = cmd[1]
            cmd = tuple(cmd[:-1])

        cmd_args = {'cmd': cmd[0]}
        for i in xrange(1, len(cmd)):
            cmd_args[str(i)] = cmd[i]

        self.wfile.write(urllib.urlencode(cmd_args))
        self.server.queue.task_done()

    def parse_querystring(self):
        path = self.path + '?'
        qs = path[path.find('?')+1:].rstrip('?')
        return parse_qs(qs)

    def translate_path(self, path):
        """Translate a /-separated PATH to the local filename syntax.

        Components that mean special things to the local file system
        (e.g. drive or directory names) are ignored.  (XXX They should
        probably be diagnosed.)

        """
        # abandon query parameters
        path = urlparse.urlparse(path)[2]
        path = posixpath.normpath(urllib.unquote(path))
        words = path.split('/')
        words = filter(None, words)
        path = os.path.dirname(__file__)
        for word in words:
            drive, word = os.path.splitdrive(word)
            head, word = os.path.split(word)
            if word in (os.curdir, os.pardir): continue
            path = os.path.join(path, word)
        return path


    def _do_nothing(*args, **kwargs):
        pass

    log_request = log_error = log_message = _do_nothing

